#include "Remote.h"
#include "Wireless.h"

#define REMOTE_DISCONNECT_TIME 1500         // 1.5s
#define REMOTE_DISCONNECT_DISABLE_TIME 5000 // 5s

static RemoteData_t g_remoteData = {0};  // 遥控器数据
static SysTime_t g_remoteUpdateTime = 0; // 遥控器数据更新时间
static bool g_remoteConnected = false;

RemoteData_t *RemoteDataGet(void)
{
    return &g_remoteData;
}

void RemoteDataSend(uint8_t *data, uint16_t len)
{
    WirelessSendData(WIRELESS_CMD_RECEIVER_DATA, (uint8_t *)data, len);
}

bool RemoteDisconnected(void)
{
    return !g_remoteConnected;
}

static void wirelessDataHandle(WirelessCmd_t cmd, unsigned char *data, unsigned short length)
{
    if (cmd == WIRELESS_CMD_REMOTE_DATA && sizeof(RemoteData_t) == length)
    {
        g_remoteConnected = true;
        memcpy(&g_remoteData, data, length);
        g_remoteUpdateTime = SysTime();
    }
}

static void disconnectHandle(void)
{
    static SysTime_t lastTime = 0;

    if (SysTimeHasPast(lastTime, 50))
    {
        if (g_remoteUpdateTime == 0 || SysTimeHasPast(g_remoteUpdateTime, REMOTE_DISCONNECT_TIME))
        {
            if (g_remoteConnected) // 断开连接
            {
                memset(&g_remoteData, 0, sizeof(RemoteData_t)); // 清除数据
                g_remoteConnected = false;
            }
        }
        lastTime = SysTime();
    }
}

uint8_t RemoteGetButtonLevel(RemoteButtonID_t btnid)
{
    uint8_t level = 0;

    switch (btnid)
    {
    case REMOTE_BTN_ID_EMERGENCY_STOP:
        level = g_remoteData.io.emergencyStop;
        break;
    case REMOTE_BTN_ID_START:
        level = g_remoteData.io.start;
        break;
    case REMOTE_BTN_ID_STOP:
        level = g_remoteData.io.stop;
        break;
    case REMOTE_BTN_ID_LIGHT:
        level = g_remoteData.io.light;
        break;
    case REMOTE_BTN_ID_HORN:
        level = g_remoteData.io.horn;
        break;
    default:
        break;
    }

    return level;
}

void RemoteReset(void)
{
    memset(g_remoteData.current, 0, sizeof(SYS_VALVE_CH_COUNT * 2));
    g_remoteData.io.start = 0;
    g_remoteData.io.stop = 0;
}

void RemoteInitialize(void)
{
    // RemoteReset();
    memset(&g_remoteData, 0, sizeof(RemoteData_t));
    WirelessInit(wirelessDataHandle);
    WirelessConflictDetectInit();
}

void RemotePoll(void)
{
    WirelessPoll();
    disconnectHandle();
}
